package com.xm.listener;

import com.xm.utils.MailUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class XmStatusListener {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送邮箱验证码
     * @param map
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "xm.code.queue"),
            exchange = @Exchange(name = "xm.direct", type = ExchangeTypes.DIRECT),
            key = "xm.code"
    ))
    public void listeneMployCode(Map<String,String> map){
        // 获取验证码
        String code = getCode();
//        存到redis
        redisTemplate.opsForValue().set(map.get("key")+code,code,3, TimeUnit.MINUTES);


        //发送验证码
        MailUtils.sendMail(map.get("email"),code,"校猫外卖邮箱验证码");
    }

    /**
     * 生成6位数验证码
     * @return
     */
    public String getCode(){
        Random random = new Random();
        String code="";
        for (int i = 0; i <6 ; i++) {
            code+=random.nextInt(10);
        }
        return code;
    }
}
